import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_elf/config/component_index.dart';
import 'package:flutter_elf/model/home_list.dart';
import 'package:flutter_elf/network/service/home_service.dart';
import 'package:flutter_elf/widgets/loading/loading_widget.dart';
import 'package:loadmore/loadmore.dart';
//斗图首页
class HomePage extends BaseWidget{
  @override
  BaseWidgetState<BaseWidget> getState() {
    // TODO: implement getState
    return HomePageState();
  }
}

class HomePageState extends BaseWidgetState<HomePage>{

  int page = 1;
  int pageSize = 20;
  bool isFinish = false;
  List<HomeListData> datas;

  @override
  void onCreate() {
    // TODO: implement onCreate
    super.onCreate();
    datas = List();
    getData();
  }


  @override
  Widget buildView(BuildContext context) {
    // TODO: implement buildView
    return Column(
      children: <Widget>[
        CachedNetworkImage(
          imageUrl: 'http://attach.bbs.miui.com/forum/month_1012/10120514509c7244b23f4a2fa5.jpg',
          height: 250,
          width: double.infinity,
        ),
        Container(
          padding: EdgeInsets.symmetric(vertical: 5,horizontal: 10),
          child: Row(
            children: <Widget>[
              Text('最新表情',style: TextStyle(fontSize: 12,color: Colors.grey),),
              Expanded(child: SizedBox(),),
              Text('更多',style: TextStyle(fontSize: 12,color: Colors.black),)
            ],
          ),
        ),
//        Expanded(
//          child: RefreshIndicator(
//            onRefresh: getData,
//            child: datas?.length == 0
//                ? Center(
//              child: Text('没有数据'),
//            )
//                : LoadMore(
//              whenEmptyLoad: true,
//              delegate: DefaultLoadMoreDelegate(),
//              textBuilder: DefaultLoadMoreTextBuilder.chinese,
//              onLoadMore: _onLoadMore,
//              isFinish: datas.length % 20 != 0 || isFinish,
//              child: ListView.builder(
//                itemBuilder: (context, i) {
//                  return buildGridViewItem(datas[i]);
//                },
//                itemCount: datas.length,
//              ),
//            ),
//          ),
//        ),

        Expanded(
          child: RefreshIndicator(
            onRefresh: getData,
            child: datas?.length == 0
                ? Center(
              child: Text('没有数据'),
            )
                : LoadMore(
              whenEmptyLoad: true,
              delegate: DefaultLoadMoreDelegate(),
              textBuilder: DefaultLoadMoreTextBuilder.chinese,
              onLoadMore: _onLoadMore,
              isFinish: datas.length % 20 != 0 || isFinish,
              child: GridView.builder(
                semanticChildCount: 4,
                gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                  //单个子Widget的水平最大宽度
                  maxCrossAxisExtent: px(300),
                  //水平单个子Widget之间间距
                  mainAxisSpacing: px(10),
                  //垂直单个子Widget之间间距
                  crossAxisSpacing: 5,
                ),
                itemCount: datas.length,
                itemBuilder: (BuildContext context, int index) {
                  return buildGridViewItem(datas[index]);
                },
              ),
            ),
          ),
        )


//        FutureBuilder<HomeListResponse>(
//          future: HomeService.homeList({"pageNum":page,"pageSize":pageSize}),
//          builder: (context,snap){
//            logs('数据长度==>' + snap?.data?.data?.length?.toString());
//            if(snap.connectionState == ConnectionState.done){
//              return Expanded(
//                child: GridView.builder(
//                  gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
//                    //单个子Widget的水平最大宽度
//                      maxCrossAxisExtent: px(300),
//                      //水平单个子Widget之间间距
//                      mainAxisSpacing: px(10),
//                      //垂直单个子Widget之间间距
//                      crossAxisSpacing: 5,
//                  ),
//                  itemCount: snap.data?.data?.length,
//                  itemBuilder: (BuildContext context, int index) {
//                    logs(snap.data.data.toString());
//                    return buildGridViewItem(snap.data?.data[index]);
//                  },
//                ),
//              );
//            }else{
//              return Expanded(child: LoadingWidget());
//            }
//          },
//        ),
      ],
    );
  }

  buildGridViewItem(HomeListData data){
    return Column(
      children: <Widget>[
        CachedNetworkImage(
          fit: BoxFit.fitHeight,
          imageUrl: data.gifPath,
          height: px(200),
          width: px(200),
        ),
        Text(data.name,style: TextStyle(fontSize: 14,color: Colors.black),maxLines: 1,)
      ],
    );
  }

  @override
  PreferredSizeWidget initAppbar() {
    // TODO: implement initAppbar
    return null;
  }

  Future<void> getData() async {
    page = 1;
    datas.clear();
    HomeListResponse response =
    await HomeService.homeList({"pageNum":page,"pageSize":pageSize},state: this);
    globalPrint('请求到的数据是' + response.toString());
    if (response?.data?.isNotEmpty ?? false) {
      page++;
      setState(() {
        datas.addAll(response?.data);
        globalPrint('一共多少条数据=== 》 ' + datas.length.toString());
        if (response?.data?.length == 0) {
          isFinish = true;
        }
      });
    }
  }

  Future<bool> _onLoadMore() async {
    HomeListResponse response =
    await HomeService.homeList({"pageNum":page,"pageSize":pageSize},state: this);
    if (response?.data?.isNotEmpty ?? false) {
      page++;
      datas.addAll(response?.data);
      loadData();
      return true;
    }
    globalPrint("接收的数据===>" + response.toString());
    if (response?.code != '0' || response?.data?.length== 0) {
      setState(() {
        isFinish = true;
      });
    }
    return false;
  }

  void loadData() {
    setState(() {});
  }

}